package edu.msu.cse.meldru20.project1;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.InputType;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint("ShowToast")
public class EditingActivity extends Activity {
	
	private int lineColor = Color.BLACK;
	
	private FrameLayout frame = null;
	
	private static final int GOT_COLOR = 1;
	
	private SeekBar lineWidthSeek = null;
	
	private int lineWidth = 1;
	
	private Toast toastLineWidth = null;
	
	private GameManager game = null;
	
	private TextView p1Score = null;
	
	private TextView p2Score = null;
	
	private boolean drawing = true;
	
	private static final String DRAWING = "drawing";
	
	private static final String LINEWIDTH = "lineWidth";
	
	private static final String LINECOLOR = "lineColor";
	
	public static final String IMAGE = "Image";
	
	public static final String TRANSFER = "transfer";
	
	private TextView category = null;
	
	private EditingView theDrawing;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_editing); 
		
		game = GameManager.get();
		
		//currentPlayer = (TextView) findViewById(R.id.textViewCurrentPlayer);
		//currentPlayer.setText(game.getPlayer1());
		p1Score = (TextView) findViewById(R.id.Player1Score);
		p2Score = (TextView) findViewById(R.id.Player2Score);
		
		category = (TextView) findViewById(R.id.textViewCategory);
		
		toastLineWidth = Toast.makeText(this, "Line width:", Toast.LENGTH_SHORT);
		
		frame = (FrameLayout) findViewById(R.id.colorFrame);
		frame.setBackgroundColor(lineColor);
		
		theDrawing = (EditingView)findViewById(R.id.editingView1);
		
		// Enable saving the drawing from the drawing view
		theDrawing.setDrawingCacheEnabled(true);
		
		lineWidthSeek = (SeekBar) findViewById(R.id.seekBarLineWidth);
		lineWidthSeek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
			
			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				if(progress > 0) {
					lineWidth = progress;
				}
				else {
					seekBar.setProgress(1);
				}
				toastLineWidth.setText("Line width:" + lineWidth);
				toastLineWidth.show();
				
				// Let the drawing view know of the new line width
				theDrawing.SetLineWidth(lineWidth);
			}
		});
		
		if(savedInstanceState != null) {
			theDrawing.getFromBundle(IMAGE, savedInstanceState);
			
			// We have saved state
			drawing = savedInstanceState.getBoolean(DRAWING);
			lineWidth = savedInstanceState.getInt(LINEWIDTH);
			lineColor = savedInstanceState.getInt(LINECOLOR);
		}
		else
		{
			// Show the mode dialog instructions
			// This will also pick the random category
			game.showInstructions(this);
		}
		
		setTitle("Round " + game.getCurrentRound() + ": " + game.getCurrentPlayer() + " is Drawing");
		
		category.setText("Category: " + game.getCurrentCategory());
		
		updateUI();
	}
	
	@Override
	protected void onSaveInstanceState(Bundle bundle) {
		super.onSaveInstanceState(bundle);
		
		theDrawing.putToBundle(IMAGE, bundle);
		
		bundle.putBoolean(DRAWING, drawing);
		bundle.putInt(LINECOLOR, lineColor);
		bundle.putInt(LINEWIDTH, lineWidth);
	}

	/*@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_editing, menu);
		return true;
	}*/
	
	public void onSubmit(View view) {
		createInfoInputDialog(view);
	}
	
	public void createInfoInputDialog(final View view) {
		final AlertDialog.Builder alert_builder = new AlertDialog.Builder(this);
		
		LinearLayout layout = new LinearLayout(this);
		layout.setOrientation(1); //1 is for vertical orientation
		final EditText name = new EditText(this); 
		final EditText hint = new EditText(this);
		name.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
		hint.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
		name.setHint("Name of the drawing");
		hint.setHint("Hint for the guesser");
		name.setText(game.getDrawingName());
		hint.setText(game.getDrawingHint());
		final TextView name_text = new TextView(this);
		final TextView hint_text = new TextView(this);
		name_text.setText("Drawing Name:");
		hint_text.setText("Hint:");
		layout.addView(name_text);
		layout.addView(name);
		layout.addView(hint_text);
		layout.addView(hint);
		alert_builder.setView(layout);
		
	    alert_builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
	        public void onClick(DialogInterface dialog, int whichButton) {
	            game.setDrawingName(name.getText().toString().trim());
	            game.setDrawingHint(hint.getText().toString().trim());
	            game.SetDrawing(theDrawing.GetDrawing());
	            if (game.getDrawingName().equals("") || game.getDrawingHint().equals("")) {
	            	Toast.makeText(getApplicationContext(), "You must provide both a name and a hint", Toast.LENGTH_SHORT).show();
	            	createInfoInputDialog(view);
	            }
	            else {
	            	//Intent intent = new Intent(getBaseContext(), GuessActivity.class);
	            	//startActivity(intent);
	            	game.advanceGame(getBaseContext());
	            }
	            
	        }
	    });

	    alert_builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
	        public void onClick(DialogInterface dialog, int whichButton) {
	            dialog.cancel();
	        }
	    });
	    
	    alert_builder.show();
	}
	
	public void onColorPicker(View view) {
		Intent intent = new Intent(this, ColorSelectActivity.class);
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    	startActivityForResult(intent, GOT_COLOR);
	}
	
	/**
     * Function called when we get a result from some external 
     * activity called with startActivityForResult()
     * @param requestCode the request code we sent to the activity 
     * @param resultCode a result of from the activity - ok or cancelled
     * @param data data from the activity
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        
        if(requestCode == GOT_COLOR && resultCode == Activity.RESULT_OK) {
        	// This is a color response
        	lineColor = data.getIntExtra(ColorSelectActivity.COLOR, Color.BLACK);
        	theDrawing.SetPaintColor(lineColor);
        	//hatterView.setColor(color);
        	updateUI();
        }
    }
    
    /**
     * Ensure the user interface components match the current state
     */
    private void updateUI() {
    	frame.setBackgroundColor(lineColor);
    	lineWidthSeek.setProgress(lineWidth);
    	
    	p1Score.setText(game.getPlayer1() + ": " + game.getPlayer1Score());
    	p2Score.setText(game.getPlayer2() + ": " + game.getPlayer2Score());
    }
    
    /*
	 * (non-Javadoc)
	 * @see android.app.Activity#onKeyDown(int, android.view.KeyEvent)
	 * Capture a "back" button press and force the user to quit back to the
	 * main menu or keep playing
	 */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) { 
        	game.handleBackButton(this);
        	return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    
    public void OnClickView(View view)
    {
    	theDrawing.SetEditable(false);
    }
    
    public void OnClickDraw(View view)
    {
    	theDrawing.SetEditable(true);
    }
	
}
